package cn.q3c.download.base;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;

import cn.keyvalue.ccf.common.util.ObjectUtils;
import cn.q3c.download.commons.DownloadLog;
import cn.q3c.download.commons.DownloadUtils;

/**
 * 清除基类，一次加载的，内部可以加一些变量缓存 根据日志删除文件，同时删除日志文件
 * 
 * @author wangxinning
 * 
 */
public class BaseClear {

	// 下载日志文件列表
	public void clear() throws IOException, ParseException {
		// 1.根据时间计算起始日志位置
		Date toDate = DateUtils.addHours(new Date(), 0 - saveLimitHour);
		Date fromDate = DateUtils.addDays(toDate, -10);

		// 2.向前探测日志，最多10天
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(fromDate);

		while (true) {
			if (calendar.getTimeInMillis() > toDate.getTime()) {
				break;
			}

			File logFile = new File(DownloadUtils.getProjectLogFile(
					projectName, calendar.getTime()));

			if (logFile.exists()) {
				List<DownloadLog> logList = DownloadUtils
						.fileToDownloadLogList(logFile);

				if (!ObjectUtils.isEmptyList(logList)) {
					for (int i = logList.size() - 1; i >= 0; i--) {
						DownloadLog log = logList.get(i);

						// 1.文件存在则删除
						if (log.getFile().exists()) {
							FileUtils.forceDelete(log.getFile());
						}

						// 2.目录空了，删上层目录
						if (log.getFile().getParentFile().isDirectory()
								&& log.getFile().getParentFile().list().length == 0) {
							FileUtils.deleteDirectory(log.getFile()
									.getParentFile());
						}
					}
				}

				FileUtils.forceDelete(logFile);// 删除日志文件
			}

			calendar.add(Calendar.HOUR, 1);
		}
	}

	// 项目名称
	private String projectName;

	public String getProjectName() {
		return projectName;
	}

	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}

	// 保留时间（小时）
	private int saveLimitHour;

	public int getSaveLimitHour() {
		return saveLimitHour;
	}

	public void setSaveLimitHour(int saveLimitHour) {
		this.saveLimitHour = saveLimitHour;
	}

	public static void main(String[] args) {
		File file = new File("\\logs\\download\\s.txt");
		System.out.println(file.getParentFile().list().length);
	}
}
